<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import registerFormConfig from "./config";
import { FormInst, useMessage } from "naive-ui";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();

const formRef = ref<FormInst | null>(null);
let isGetCode = ref<boolean>(false);
const message = useMessage();
// 注册
const register = () => {
	const instance: Record<string, any> = formRef?.value?.getFormRef();
	instance.validate((err) => {
		if (!err) {
			if (instance.model.password !== instance.model.comfirPassword) {
				message.error("密码与确认密码不一致");
				return;
			}
			const data = {
				account: instance.model.account,
				email: instance.model.email,
				password: instance.model.password,
				code: instance.model.code,
				is_admin:0
			}
			console.log(data);
			
			userStore.register(data);
		} else {
			// 密码与确认密码、验证码确定
			message.error("注册失败");
		}
	});
};

let timer;
let second = ref<number>(60);
// 获取邮箱验证码
const getEamilCode = async () => {
	const instance: Record<string, any> = formRef?.value?.getFormRef();
	let email = instance.model.email;
	let err = instance.rules.email.validator({}, email);
	if (err instanceof Error) {
		window.$message.error("请填写正确的邮箱");
		return;
	} else {
		if (timer) {
			return;
		}
		isGetCode.value = true;

		timer = setInterval(() => {
			second.value--;
			if (second.value === 0) {
				clearInterval(timer);
				timer = null;
				second.value = 60;
				isGetCode.value = false;
			}
		}, 1000);

		userStore.getEamilCode({
			email,
		});
	}
};

const reset = () => {
	formRef?.value?.reset();
};
</script>

<template>
	<Form :config="registerFormConfig" ref="formRef"></Form>
	<n-space>
		<n-button
			v-debounce="getEamilCode"
			type="info"
			class="btn"
			v-if="!isGetCode"
			>获取验证码</n-button
		>
		<n-button v-else v-debounce="getEamilCode" type="info" class="btn" disabled
			>获取验证码({{ second }})</n-button
		>
		<n-button v-debounce="register" type="info" class="btn">注册</n-button>
		<n-button v-debounce="reset" type="info" class="btn">重置</n-button>
	</n-space>
</template>

<style lang="less" scoped>
@import "@/styles/mixin.less";
.btn {
	width: 125px;
}
</style>
